<?php	
		error_reporting(E_ALL);
		session_start();
		if (!isset($_GET['id']) || !isset($_GET['token']) ) die('Need id and token');

		$ch = curl_init();  

		$token = isset($_SESSION['GoogleToken']) ? $_SESSION['GoogleToken'] : $_GET['token'];
		$url = "https://spreadsheets.google.com/feeds/worksheets/{$_GET['id']}/private/full";//auth=".$token;
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, false);   
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		    'Authorization: Bearer '. $token,
		    'Access-Control-Allow-Origin: *'
		    ));
		//echo $url;

		$output = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if($httpCode == 200) {
    		$_SESSION['GoogleToken'] = $_GET['token'];
		}
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		header("HTTP/1.0 " . $httpCode);
		if($errno = curl_errno($ch)) {
		    echo "cURL error ({$errno})";
		}
		curl_close($ch);


		$xml = new SimpleXMLElement($output); 
		$xml->registerXPathNamespace("a", "http://www.w3.org/2005/Atom");
		//echo $output;
		//var_dump($xml);
		foreach( $xml->xpath("//a:entry[a:title='Output']/a:link[@rel='http://schemas.google.com/spreadsheets/2006#cellsfeed']") as $elem)
			$url =	($elem['href']);
		// //feed/entry[title='Output'] $movies->xpath("//feed/entry[title='Output']") as $character


		$ch = curl_init();  

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, false);   
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		    'Authorization: Bearer '. $token,
		    'Access-Control-Allow-Origin: *'
		    ));
		//echo $url;

		$output = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		header("HTTP/1.0 " . $httpCode);
		if($errno = curl_errno($ch)) {
		    echo "cURL error ({$errno})";
		}

		curl_close($ch);

		$xml = new SimpleXMLElement($output); 
		$xml->registerXPathNamespace("a", "http://www.w3.org/2005/Atom");
		//var_dump($xml);
		foreach( $xml->xpath("//a:entry[a:title='A1']") as $elem)
			echo ($elem->content);
?>